package com.qs.rocketmq.order.listener;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.qs.rocketmq.common.util.ResultObject;
import com.qs.rocketmq.order.dto.OrderDTO;
import com.qs.rocketmq.order.service.OrderService;
import com.qs.rocketmq.order.service.TransactionService;
import com.qs.rocketmq.order.util.OrderConstant;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Component;


@Component
@Slf4j
@RocketMQTransactionListener
public class OrderProducerTxListenerImpl implements RocketMQLocalTransactionListener {

    @Autowired
    private OrderService orderService;

    @Autowired
    private TransactionService transactionService;

    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message msg, Object arg) {
        ResultObject<Object> resultObject = new ResultObject<>();
        log.info("开始执行本地事务，msg={}，arg={}", msg, arg);
        byte[] payload = (byte[]) msg.getPayload();
        OrderDTO orderDTO = JSONUtil.toBean(StrUtil.str(payload, "utf-8"), OrderDTO.class);
        orderDTO.setTransactionId(msg.getHeaders().get("rocketmq_TRANSACTION_ID", String.class));
        // 根据keys来区分哪个事务消息
        String keys = msg.getHeaders().get("rocketmq_KEYS", String.class);
        if(OrderConstant.REQ_CODE_CREATE_ORDER.equals(keys)){
            resultObject = orderService.doCreateOrder(orderDTO);
            if (!resultObject.isSuccess()) {
                return RocketMQLocalTransactionState.ROLLBACK;
            }
        }

        return RocketMQLocalTransactionState.UNKNOWN;
    }

    // 通过事务消息回查，判断事务消息表中数据状态，判断在 executeLocalTransaction 方法中创建订单是否成功
    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message msg) {
        log.info("开始回查：{}", msg);
        String transactionId = msg.getHeaders().get("rocketmq_TRANSACTION_ID", String.class);
        System.out.println("transactionId=" + transactionId);
        if (transactionService.checkTransactionStatus(transactionId)) {
            return RocketMQLocalTransactionState.COMMIT;
        } else {
            return RocketMQLocalTransactionState.ROLLBACK;
        }
    }
}
